<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */

namespace app\mobile\controller;

use app\admin\model\FigureDistribution;

use app\admin\model\FigureShareholderLog;
use app\BaseController;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureMemberSet;
use app\admin\model\FigureMember;
use app\admin\model\FigureMemberLog;
use app\admin\model\FigureUser;
use app\admin\model\FigureSystem;
use app\admin\model\FigureCard;
use app\admin\model\FigureBrokerageSet;
use app\admin\model\FigureBrokerageLog;
use app\admin\model\FigureBalanceLog;
use app\admin\model\FigurePointSet;
use app\admin\model\FigurePoint;
use app\admin\model\FigurePointLog;
use app\admin\model\template\MemberBuySuccess;
use app\admin\model\template\MemberRenewSuccess;
use app\admin\model\template\IntegralArrival;
use app\admin\model\FigureCardLog;
use app\admin\model\template\OpenMember;
use app\admin\model\template\RechargeSuccess;
use app\admin\model\FigurePartner;

/**
 * 会员操作
 *
 * @author Administrator
 *
 */
class Member extends BaseController
{

    /**
     * 测试
     * http://aigc.weijuyunke.cn/mobile/member/test
     */
    public function test()
    {
        $log = FigureMemberLog::where('id', 22)->find();
        $this->commission($log);
    }

    /**
     * 会员设置
     * http://aigc.weijuyunke.cn/mobile/member/set
     */
    public function set()
    {
        $set = FigureMemberSet::where("id", 1)->find();

        if (empty($set)) {
            $set = [];
        }

        if (!empty($set['rights'])) {
            $set['rights'] = html_entity_decode($set['rights'], ENT_QUOTES);
        }

        return result(0, 'success', $set);
    }

    /**
     * 会员列表
     * http://aigc.weijuyunke.cn/mobile/member/memberList
     *
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function memberList()
    {
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        $where = " is_display = 1 ";

        $total = FigureMember::where($where)->count();

        if ($total) {
            $list = FigureMember::where($where)->order([
                "is_recommend" => "ASC",
                "sort" => "DESC"
            ])
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 购买会员
     * http://aigc.weijuyunke.cn/mobile/member/addMemberLog
     *
     * @param
     *            uid 用户id
     * @param
     *            member_id 会员id
     */
    public function addMemberLog()
    {
        $uid = input('uid');
        $member_id = input('member_id');

        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
        }

        $member = FigureMember::where('id', $member_id)->find();
        if (empty($member)) {
            return result(-1, '会员不存在');
        }

        $log_no = getPayNo('ME');
        $data = array(
            'log_no' => $log_no,
            'member_id' => $member['id'],
            'type' => 1,
            'uid' => $uid,
            'name' => $member['name'],
            'money' => $member['money'],
            'day' => $member['day'],
            'point' => $member['point'],
            'avatar_twin_count' => $member['avatar_twin_count'],
            'voice_twin_count' => $member['voice_twin_count'],
            'second' => $member['second'],
            'second_infinite' => $member['second_infinite'],
            'high_fidelity_words_number' => $member['high_fidelity_words_number'],
            'ai_copywriting_times' => $member['ai_copywriting_times'],
            'xunfei_fidelity_words_number' => $member['xunfei_fidelity_words_number'],
            'xunfei_sound_clone_words_number' => $member['xunfei_sound_clone_words_number'],
            'ai_title_times' => $member['ai_title_times'],
            'pay_status' => 1,
        );
        $log = new FigureMemberLog();
        $log->save($data);

        return result(0, '购买成功', $log_no);
    }

    public static function update_member($log_no, $price)
    {
        Db::startTrans();
        try {

            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }
            $log = FigureMemberLog::where('log_no', $log_no)->find();
            if ($log['pay_status'] == 2) {
                exit();
            }
            $redisLog = $redis->get("memberLog-" . $log_no);
            if ($redisLog) {
                exit();
            }
            $redis->set("memberLog-" . $log_no, 1);
            $redis->persist("memberLog-" . $log_no);
            $log['money'] = (float)$log['money'];
            $price = (float)$price;
            if (bccomp($log['money'], $price, 2) != 0) {
                Log::error("Member update_member  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            $uid = $log['uid'];
            $user = FigureUser::where("id", $uid)->find();


            if ($log['second_infinite'] == 1) {
                FigureUser::where("id", $uid)->save([
                    'second_infinite' => 1
                ]);
            } else {
                if (!empty($log['second'])) {
                    $balanceLog = new FigureBalanceLog();
                    $balanceLog->save([
                        'uid' => $uid,
                        'log_no' => $log_no,
                        'type' => 1,
                        'way' => 6,
                        'b_type' => 3,
                        'current' => $user['second'],
                        'money' => $log['second'],
                        'desc' => '购买 ' . $log['name']
                    ]);
                    FigureUser::where("id", $uid)->save([
                        'second' => Db::raw('second+' . $log['second'])
                    ]);
                }
            }
            if (!empty($log['voice_twin_count'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 3,
                    'b_type' => 2,
                    'current' => $user['voice_twin_count'],
                    'money' => $log['voice_twin_count'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'voice_twin_count' => Db::raw('voice_twin_count+' . $log['voice_twin_count'])
                ]);
            }
            if (!empty($log['high_fidelity_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 14,
                    'b_type' => 4,
                    'current' => $user['high_fidelity_words_number'],
                    'money' => $log['high_fidelity_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'high_fidelity_words_number' => Db::raw('high_fidelity_words_number+' . $log['high_fidelity_words_number'])
                ]);
            }
            if (!empty($log['ai_copywriting_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 8,
                    'b_type' => 2,
                    'current' => $user['ai_copywriting_times'],
                    'money' => $log['ai_copywriting_times'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_copywriting_times' => Db::raw('ai_copywriting_times+' . $log['ai_copywriting_times'])
                ]);
            }

            if (!empty($log['xunfei_fidelity_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 16,
                    'b_type' => 4,
                    'current' => $user['xunfei_sound_generate_words_number'],
                    'money' => $log['xunfei_fidelity_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_generate_words_number' => Db::raw('xunfei_sound_generate_words_number+' . $log['xunfei_fidelity_words_number'])
                ]);
            }

            if (!empty($log['xunfei_sound_clone_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 15,
                    'b_type' => 2,
                    'current' => $user['xunfei_sound_clone_words_number'],
                    'money' => $log['xunfei_sound_clone_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_clone_words_number' => Db::raw('xunfei_sound_clone_words_number+' . $log['xunfei_sound_clone_words_number'])
                ]);
            }


            if (!empty($log['ai_title_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 17,
                    'b_type' => 2,
                    'current' => $user['ai_title_times'],
                    'money' => $log['ai_title_times'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_title_times' => Db::raw('ai_title_times+' . $log['ai_title_times'])
                ]);
            }

            if (!empty($log['point'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 1,
                    'current' => $user['balance'],
                    'money' => $log['point'],
                    'desc' => '购买 ' . $log['name'].'金额'.$log['money']
                ]);

                FigureUser::where("id", $uid)->save([
                    'balance' => Db::raw('balance+' . $log['point'])
                ]);
            }


            $name = '';
            $maturity_time = 0;
            if (!empty($log['day'])) {
                $type = 0;
                if ($user['is_member']) {
                    $type = 1;
                    $maturity_time = strtotime("+" . $log['day'] . " day", strtotime($user['maturity_time'])) + 86399;
                    $name = "续费" . $log['name'];
                } else {
                    $maturity_time = strtotime("+" . $log['day'] . " day", strtotime(date("Y-m-d"))) + 86399;
                    $name = "开通" . $log['name'];
                }
                $user->is_member = 1;
                $user->maturity_time = $maturity_time;
                $user->save();
            }

            FigureMemberLog::where('log_no', $log_no)->update([
                'pay_status' => 2
            ]);
            $openMember = new OpenMember([
                'openid' => $user['openid'],
                'name' => $name,
                'type' => '会员充值',
                'money' => $log['money'],
                'time' => date("Y-m-d", $maturity_time),
                'code' => '无'
            ]);
            $openMember->send();

            // 分销
            $setting = FigureBrokerageSet::where('id', 1)->find();

            if (isset($setting) && $setting['is_open'] == 1 && $user['pid'] > 0 && ($setting['distribution_mode'] == 1 || $setting['distribution_mode'] == 2)) { // 分销开启

                self::getUserDistributionLevelAndCommission($user, $setting, $log['money'], $log_no, 2);
                /*   $commission = array();
                   $pid = array();

                   switch ($setting['is_level']) {
                       case 1:
                           $commission[0] = $price * $setting['oneLevel'] * 0.01;
                           break;
                       case 2:
                           $commission[0] = $price * $setting['oneLevel'] * 0.01;
                           $commission[1] = $price * $setting['twoLevel'] * 0.01;
                           break;
                       default:
                           $commission = array();
                           break;
                   }

                   $pid[0] = FigureUser::where('id', $uid)->value('pid');

                   if (! empty($pid[0])) {
                       $pid[1] = FigureUser::where('id', $pid[0])->value('pid');
                   }
                   if (! empty($pid[1])) {
                       $pid_three = FigureUser::where('id', $pid[1])->value('pid');
                       if (! empty($pid_three)) {
                           $pid[2] = $pid_three;
                       }
                   }

                   $brokerageLog = [];
                   $pointLog = [];

                   if (! empty($commission) && ! empty($pid)) {

                       $t = time();
                       foreach ($commission as $k => $v) {
                           if ($v < 0.01 || empty($pid[$k])) {
                               continue;
                           }

                           $brokerage = FigureBrokerageLog::where([
                               'log_no' => $log_no,
                               'type' => 2,
                               'pid' => $pid[$k],
                               'uid' => $uid
                           ])->find();
                           if (! empty($brokerage)) {
                               continue;
                           }

                           $pUser = FigureUser::where('id', $pid[$k])->find();

                           if ($pUser) {
                               $brokerageLog[] = [
                                   'log_no' => $log_no,
                                   'type' => 2,
                                   'pid' => $pid[$k],
                                   'uid' => $uid,
                                   'total' => $price,
                                   'money' => $v,
                                   'create_time' => $t
                               ];

                               $pUser->save([
                                   'brokerage' => Db::raw('brokerage+' . $v)
                               ]);
                           }
                       }
                   }

                   if (! empty($brokerageLog)) {
                       $brokerage = new FigureBrokerageLog();
                       $brokerage->saveAll($brokerageLog);
                   }*/
            }


            $redis->del("memberLog-" . $log_no);
            // 关闭连接
            $redis->close();

            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            Log::error("Member update_member 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }
    }

    public static function update_member_test()
    {
        Db::startTrans();
        $log_no = 'ME2025090210098485';
        $price = '1';
     /*   try {*/

            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }
            $log = FigureMemberLog::where('log_no', $log_no)->find();
            if ($log['pay_status'] == 2) {
                exit();
            }
            $redisLog = $redis->get("memberLog-" . $log_no);
            if ($redisLog) {
                exit();
            }
            $redis->set("memberLog-" . $log_no, 1);
            $redis->persist("memberLog-" . $log_no);
            $log['money'] = (float)$log['money'];
            $price = (float)$price;
            if (bccomp($log['money'], $price, 2) != 0) {
                Log::error("Member update_member  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            $uid = $log['uid'];
            $user = FigureUser::where("id", $uid)->find();


            if ($log['second_infinite'] == 1) {
                FigureUser::where("id", $uid)->save([
                    'second_infinite' => 1
                ]);
            } else {
                if (!empty($log['second'])) {
                    $balanceLog = new FigureBalanceLog();
                    $balanceLog->save([
                        'uid' => $uid,
                        'log_no' => $log_no,
                        'type' => 1,
                        'way' => 6,
                        'b_type' => 3,
                        'current' => $user['second'],
                        'money' => $log['second'],
                        'desc' => '购买 ' . $log['name']
                    ]);
                    FigureUser::where("id", $uid)->save([
                        'second' => Db::raw('second+' . $log['second'])
                    ]);
                }
            }
            if (!empty($log['voice_twin_count'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 3,
                    'b_type' => 2,
                    'current' => $user['voice_twin_count'],
                    'money' => $log['voice_twin_count'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'voice_twin_count' => Db::raw('voice_twin_count+' . $log['voice_twin_count'])
                ]);
            }
            if (!empty($log['high_fidelity_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 14,
                    'b_type' => 4,
                    'current' => $user['high_fidelity_words_number'],
                    'money' => $log['high_fidelity_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'high_fidelity_words_number' => Db::raw('high_fidelity_words_number+' . $log['high_fidelity_words_number'])
                ]);
            }
            if (!empty($log['ai_copywriting_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 8,
                    'b_type' => 2,
                    'current' => $user['ai_copywriting_times'],
                    'money' => $log['ai_copywriting_times'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_copywriting_times' => Db::raw('ai_copywriting_times+' . $log['ai_copywriting_times'])
                ]);
            }

            if (!empty($log['xunfei_fidelity_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 16,
                    'b_type' => 4,
                    'current' => $user['xunfei_sound_generate_words_number'],
                    'money' => $log['xunfei_fidelity_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_generate_words_number' => Db::raw('xunfei_sound_generate_words_number+' . $log['xunfei_fidelity_words_number'])
                ]);
            }

            if (!empty($log['xunfei_sound_clone_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 15,
                    'b_type' => 2,
                    'current' => $user['xunfei_sound_clone_words_number'],
                    'money' => $log['xunfei_sound_clone_words_number'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_clone_words_number' => Db::raw('xunfei_sound_clone_words_number+' . $log['xunfei_sound_clone_words_number'])
                ]);
            }

            if (!empty($log['ai_title_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 16,
                    'b_type' => 2,
                    'current' => $user['ai_title_times'],
                    'money' => $log['ai_title_times'],
                    'desc' => '购买 ' . $log['name']
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_title_times' => Db::raw('ai_title_times+' . $log['ai_title_times'])
                ]);
            }
            $name = '';
            $maturity_time = 0;
            if (!empty($log['day'])) {
                $type = 0;
                if ($user['is_member']) {
                    $type = 1;
                    $maturity_time = strtotime("+" . $log['day'] . " day", strtotime($user['maturity_time'])) + 86399;
                    $name = "续费" . $log['name'];
                } else {
                    $maturity_time = strtotime("+" . $log['day'] . " day", strtotime(date("Y-m-d"))) + 86399;
                    $name = "开通" . $log['name'];
                }
                $user->is_member = 1;
                $user->maturity_time = $maturity_time;
                $user->save();
            }

            FigureMemberLog::where('log_no', $log_no)->update([
                'pay_status' => 2
            ]);
            $openMember = new OpenMember([
                'openid' => $user['openid'],
                'name' => $name,
                'type' => '会员充值',
                'money' => $log['money'],
                'time' => date("Y-m-d", $maturity_time),
                'code' => '无'
            ]);
            $openMember->send();

            // 分销
            $setting = FigureBrokerageSet::where('id', 1)->find();

            if (isset($setting) && $setting['is_open'] == 1 && $user['pid'] > 0 && ($setting['distribution_mode'] == 1 || $setting['distribution_mode'] == 2)) { // 分销开启

                self::getUserDistributionLevelAndCommission($user, $setting, $log['money'], $log_no, 2);
                /*   $commission = array();
                   $pid = array();

                   switch ($setting['is_level']) {
                       case 1:
                           $commission[0] = $price * $setting['oneLevel'] * 0.01;
                           break;
                       case 2:
                           $commission[0] = $price * $setting['oneLevel'] * 0.01;
                           $commission[1] = $price * $setting['twoLevel'] * 0.01;
                           break;
                       default:
                           $commission = array();
                           break;
                   }

                   $pid[0] = FigureUser::where('id', $uid)->value('pid');

                   if (! empty($pid[0])) {
                       $pid[1] = FigureUser::where('id', $pid[0])->value('pid');
                   }
                   if (! empty($pid[1])) {
                       $pid_three = FigureUser::where('id', $pid[1])->value('pid');
                       if (! empty($pid_three)) {
                           $pid[2] = $pid_three;
                       }
                   }

                   $brokerageLog = [];
                   $pointLog = [];

                   if (! empty($commission) && ! empty($pid)) {

                       $t = time();
                       foreach ($commission as $k => $v) {
                           if ($v < 0.01 || empty($pid[$k])) {
                               continue;
                           }

                           $brokerage = FigureBrokerageLog::where([
                               'log_no' => $log_no,
                               'type' => 2,
                               'pid' => $pid[$k],
                               'uid' => $uid
                           ])->find();
                           if (! empty($brokerage)) {
                               continue;
                           }

                           $pUser = FigureUser::where('id', $pid[$k])->find();

                           if ($pUser) {
                               $brokerageLog[] = [
                                   'log_no' => $log_no,
                                   'type' => 2,
                                   'pid' => $pid[$k],
                                   'uid' => $uid,
                                   'total' => $price,
                                   'money' => $v,
                                   'create_time' => $t
                               ];

                               $pUser->save([
                                   'brokerage' => Db::raw('brokerage+' . $v)
                               ]);
                           }
                       }
                   }

                   if (! empty($brokerageLog)) {
                       $brokerage = new FigureBrokerageLog();
                       $brokerage->saveAll($brokerageLog);
                   }*/
            }


            $redis->del("memberLog-" . $log_no);
            // 关闭连接
            $redis->close();

            Db::commit();
      /*  } catch (\Exception $e) {
            echo $e->getMessage();
            Db::rollback();
            Log::error("Member update_member 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }*/
    }

    /**
     * 使用卡密
     * http://aigc.weijuyunke.cn/mobile/member/useCard
     *
     * @param
     *            uid 用户id
     * @param
     *            card 卡密
     */
    public function useCard()
    {
        Db::startTrans();
        try {
            $uid = input('uid');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
                exit();
            }

            $card = FigureCard::where('card', input('card'))->find();

            if (empty($card)) {
                return result(-1, '该卡密不存在');
                exit();
            }

            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }

            if ($card['is_status'] == 2) {
                return result(-1, '该卡密已被使用');
                exit();
            }

            $redisLog = $redis->get("card-" . $card);

            if ($redisLog) {
                return result(-1, '该卡密已使用');
                exit();
            }

            $redis->set("card-" . $card, 1);
            $redis->persist("card-" . $card);

            $member = FigureMember::where('id', $card['member_id'])->find();
            $name = empty($member['name']) ? $card['member_name'] : $member['name'];

            $log_no = getPayNo("CA");

            $memberLog = new FigureMemberLog();
            $memberLog->save(array(
                'log_no' => $log_no,
                'member_id' => $card['member_id'],
                'type' => 2,
                'uid' => $uid,
                'name' => $name,
                'money' => 0,
                'day' => $card['day'],
                'point' => $card['point'],
                'avatar_twin_count' => $card['avatar_twin_count'],
                'voice_twin_count' => $card['voice_twin_count'],
                'second' => $card['second'],
                'second_infinite' => $card['second_infinite'],
                'high_fidelity_words_number' => $card['high_fidelity_words_number'],
                'ai_copywriting_times' => $card['ai_copywriting_times'],
                'xunfei_fidelity_words_number' => $card['xunfei_fidelity_words_number'],
                'xunfei_sound_clone_words_number' => $card['xunfei_sound_clone_words_number'],
                'ai_title_times' => $card['ai_title_times'],
                'card' => input('card'),
                'pay_status' => 2
            ));

            if (!empty($card['point'])) {

                $log = new FigureBalanceLog();
                $log->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 7,
                    'current' => $user['balance'],
                    'money' => $card['point'],
                    'desc' => '使用  ' . $name . '  卡密',
                    'card' => input('card')
                ]);

                FigureUser::where("id", $uid)->save([
                    'balance' => Db::raw('balance+' . $card['point'])
                ]);

                $rechargeSuccess = new RechargeSuccess([
                    'openid' => $user['openid'],
                    'name' => $name,
                    'type' => '点数卡密',
                    'money' => $card['point'],
                    'remain' => round($user['balance'] + $card['point'], 2),
                    'time' => date('Y-m-d H:i', time())
                ]);
                $rechargeSuccess->send();
            }

            if ($card['second_infinite'] == 1) {
                FigureUser::where("id", $uid)->save([
                    'second_infinite' => 1
                ]);
            } else {
                if (!empty($card['second'])) {

                    $balanceLog = new FigureBalanceLog();
                    $balanceLog->save([
                        'uid' => $uid,
                        'log_no' => $log_no,
                        'type' => 1,
                        'way' => 6,
                        'b_type' => 3,
                        'current' => $user['second'],
                        'money' => $card['second'],
                        'desc' => '使用 ' . $name . ' 卡密',
                        'card' => input('card')
                    ]);

                    FigureUser::where("id", $uid)->save([
                        'second' => Db::raw('second+' . $card['second'])
                    ]);
                }
            }

            if (!empty($card['avatar_twin_count'])) {

                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 7,
                    'b_type' => 2,
                    'current' => $user['avatar_twin_count'],
                    'money' => $card['avatar_twin_count'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);

                FigureUser::where("id", $uid)->save([
                    'avatar_twin_count' => Db::raw('avatar_twin_count+' . $card['avatar_twin_count'])
                ]);
            }
            if (!empty($card['voice_twin_count'])) {

                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 7,
                    'b_type' => 2,
                    'current' => $user['voice_twin_count'],
                    'money' => $card['voice_twin_count'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);

                FigureUser::where("id", $uid)->save([
                    'voice_twin_count' => Db::raw('voice_twin_count+' . $card['voice_twin_count'])
                ]);
            }
            if (!empty($card['high_fidelity_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 14,
                    'b_type' => 4,
                    'current' => $user['high_fidelity_words_number'],
                    'money' => $card['high_fidelity_words_number'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);
                FigureUser::where("id", $uid)->save([
                    'high_fidelity_words_number' => Db::raw('high_fidelity_words_number+' . $card['high_fidelity_words_number'])
                ]);
            }
            if (!empty($card['ai_copywriting_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 8,
                    'b_type' => 2,
                    'current' => $user['ai_copywriting_times'],
                    'money' => $card['ai_copywriting_times'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_copywriting_times' => Db::raw('ai_copywriting_times+' . $card['ai_copywriting_times'])
                ]);
            }

            if (!empty($card['xunfei_sound_generate_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 16,
                    'b_type' => 4,
                    'current' => $user['xunfei_sound_generate_words_number'],
                    'money' => $card['xunfei_sound_generate_words_number'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_generate_words_number' => Db::raw('xunfei_sound_generate_words_number+' . $card['xunfei_sound_generate_words_number'])
                ]);
            }

            if (!empty($card['xunfei_sound_clone_words_number'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 15,
                    'b_type' => 2,
                    'current' => $user['xunfei_sound_clone_words_number'],
                    'money' => $card['xunfei_sound_clone_words_number'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);
                FigureUser::where("id", $uid)->save([
                    'xunfei_sound_clone_words_number' => Db::raw('xunfei_sound_clone_words_number+' . $card['xunfei_sound_clone_words_number'])
                ]);
            }

            if (!empty($card['ai_title_times'])) {
                $balanceLog = new FigureBalanceLog();
                $balanceLog->save([
                    'uid' => $uid,
                    'log_no' => $log_no,
                    'type' => 1,
                    'way' => 17,
                    'b_type' => 2,
                    'current' => $user['ai_title_times'],
                    'money' => $card['ai_title_times'],
                    'desc' => '使用 ' . $name . ' 卡密',
                    'card' => input('card')
                ]);
                FigureUser::where("id", $uid)->save([
                    'ai_title_times' => Db::raw('ai_title_times+' . $card['ai_title_times'])
                ]);
            }
            if (!empty($card['day'])) {

                $type = 0;
                if ($user['is_member']) {
                    $type = 1;
                    $maturity_time = strtotime("+" . $card['day'] . " day", strtotime($user['maturity_time'])) + 86399;
                    $name = "续费" . $card['name'];
                } else {
                    $maturity_time = strtotime("+" . $card['day'] . " day", strtotime(date("Y-m-d"))) + 86399;
                    $name = "开通" . $card['name'];
                }
                $user->is_member = 1;
                $user->maturity_time = $maturity_time;
                $user->save();

                $openMember = new OpenMember([
                    'openid' => $user['openid'],
                    'name' => $name,
                    'type' => '会员充值',
                    'money' => 0,
                    'time' => date("Y-m-d", $maturity_time),
                    'code' => input('card')
                ]);
                $openMember->send();
            }

            $pUser = array();
            if (!empty($user['pid'])) {
                $pUser = FigureUser::where('id', $user['pid'])->find();
            }

            if (empty($pUser) && !empty($card['partner_id'])) {

                $cardPartner = FigurePartner::where('id', $card['partner_id'])->find();
                if (isset($cardPartner)) {
                    $cardPartnerUser = FigureUser::where('id', $cardPartner['uid'])->find();
                    if (isset($cardPartnerUser)) {
                        FigureUser::where([
                            'id' => $uid
                        ])->update([
                            'pid' => $cardPartner['uid']
                        ]);
                    }
                }
            }

            FigureCard::where('card', input('card'))->update([
                'is_status' => 2,
                'uid' => $uid,
                'use_time' => time()
            ]);

            FigureCardLog::where('id', $card['log_id'])->save([
                'already' => Db::raw('already+' . 1)
            ]);

            $redis->del("card-" . $card);
            // 关闭连接
            $redis->close();

            Db::commit();
            return result(0, '使用成功');
        } catch (\Exception $e) {
            Db::rollback();
            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 会员开通记录
     * http://aigc.weijuyunke.cn/mobile/member/logList
     *
     * @param
     *            uid 用户id
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function logList()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
            exit();
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        $where[] = [
            'uid',
            '=',
            $uid
        ];
        $where[] = [
            'pay_status',
            '=',
            2
        ];

        $total = FigureMemberLog::where($where)->count();
        if ($total) {
            $list = FigureMemberLog::where($where)->order('id', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 点数设置
     * http://aigc.weijuyunke.cn/mobile/member/pointSet
     */
    public function pointSet()
    {
        $set = FigurePointSet::where("id", 1)->find();

        if (empty($set)) {
            $set = [];
        }

        if (!empty($set['explain'])) {
            $set['explain'] = html_entity_decode($set['explain'], ENT_QUOTES);
        }

        return result(0, 'success', $set);
    }

    /**
     * 点数列表
     * http://aigc.weijuyunke.cn/mobile/member/pointList
     */
    public function pointList()
    {
        $member = FigurePoint::where("is_display", 1)->order("sort", "desc")->select();

        return result(0, 'success', $member);
    }

    /**
     * 购买点数
     * http://aigc.weijuyunke.cn/mobile/member/addPointLog
     *
     * @param
     *            uid 用户id
     * @param
     *            point_id 点数id
     */
    public function addPointLog()
    {
        try {
            $uid = input('uid');
            $point_id = input('point_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(-1, '用户不存在');
            }

            $point = FigurePoint::where('id', $point_id)->find();
            if (empty($point)) {
                return result(-1, '点数不存在');
            }

            $log_no = getPayNo('PT');

            $data = array(
                'uid' => $uid,
                'log_no' => $log_no,
                'point_id' => $point['id'],
                'name' => $point['name'],
                'point' => $point['point'],
                'gift' => $point['gift'],
                'money' => $point['money'],
                'pay_status' => 1
            );

            $log = new FigurePointLog();
            $log->save($data);

            return result(0, '购买成功', $log_no);
        } catch (\Exception $e) {

            return result(-1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 点数购买记录
     * http://aigc.weijuyunke.cn/mobile/member/pointLog
     *
     * @param
     *            uid 用户id
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function pointLog()
    {
        $uid = input('uid');
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(-1, '用户不存在');
            exit();
        }

        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));

        $where[] = [
            'uid',
            '=',
            $uid
        ];
        $where[] = [
            'pay_status',
            '=',
            2
        ];

        $total = FigurePointLog::where($where)->count();
        if ($total) {
            $list = FigurePointLog::where($where)->order('id', 'desc')
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }

        $totalPage = ceil($total / $psize);

        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public static function update_point($log_no, $price)
    {
        Db::startTrans();
        try {

            $redis = new \Redis();
            $password = isset(config('redis')["password"]) ? config('redis')["password"] : '';
            $port = empty(config('redis')["port"]) ? '6379' : config('redis')["port"];
            $redis->connect('127.0.0.1', $port);
            if (!empty($password)) {
                $redis->auth($password);
            }
            $log = FigurePointLog::where('log_no', $log_no)->find();

            if ($log['pay_status'] == 2) {

                exit();
            }
            $redisLog = $redis->get("pointLog-" . $log_no);

            if ($redisLog) {

                exit();
            }

            $redis->set("pointLog-" . $log_no, 1);
            $redis->persist("pointLog-" . $log_no);

            $log['money'] = (float)$log['money'];
            $price = (float)$price;

            if (bccomp($log['money'], $price, 2) != 0) {

                Log::error("Member update_point  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }


            $uid = $log['uid'];

            $total = round($log['point'] + $log['gift'], 2);

            $user = FigureUser::where("id", $uid)->find();

            $balanceLog = new FigureBalanceLog();
            $balanceLog->save([
                'uid' => $uid,
                'log_no' => $log_no,
                'type' => 1,
                'way' => 1,
                'current' => $user['balance'],
                'money' => $total,
                'desc' => '购买  ' . $log['name'].'金额'.$log['money']
            ]);

            $rechargeSuccess = new RechargeSuccess([
                'openid' => $user['openid'],
                'name' => $log['name'],
                'type' => '点数充值',
                'money' => $total,
                'remain' => round($user['balance'] + $total, 2),
                'time' => date('Y-m-d H:i', time())
            ]);
            $rechargeSuccess->send();

            $user->save([
                'balance' => Db::raw('balance+' . $total)
            ]);
            FigurePointLog::where('log_no', $log_no)->update([
                'pay_status' => 2
            ]);
            // 分销
            $setting = FigureBrokerageSet::where('id', 1)->find();

            if (isset($setting) && $setting['is_open'] == 1 && $user['pid'] > 0 && ($setting['distribution_mode'] == 1 || $setting['distribution_mode'] == 2)) { // 分销开启
                self::getUserDistributionLevelAndCommission($user, $setting, $log['money'], $log_no, 3);

            }
            $redis->del("pointLog-" . $log_no);
            // 关闭连接
            $redis->close();

            Db::commit();
        } catch (\Exception $e) {
            echo $e->getMessage();
            exit;
            Db::rollback();
            Log::error("Member update_point 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }
    }

    public static function getUserDistributionLevelAndCommission($user, $setting, $amount, $log_no, $type)
    {

        $userModel = new FigureUser();

        // 上级用户 详情
        $oneLevelUserInfo = $userModel->where(['id' => $user['pid']])->find();
        // 查看次用户总共充值了多少次
        $memberLogCount = FigureMemberLog::where(['uid' => $user['id'], 'pay_status' => 2])->count();
        $pointLogCount = FigurePointLog::where(['uid' => $user['id'], 'pay_status' => 2])->count();
        $totalCount = $memberLogCount + $pointLogCount;
        //分销
        $oneCommission = 0;
        $twoCommission = 0;
        // 股东
        //  上级等级
        $one_distribution_level = 0;
        $one_distribution_level_id = 0;
        $two_distribution_level = 0;
        $two_distribution_level_id = 0;
        $DistributionModel = new FigureDistribution();
        if ($setting['is_level'] >= 1) {
            $one_distribution_level = $oneLevelUserInfo['distribution_level'];
            $one_distribution_level_id = $oneLevelUserInfo['distribution_level_id'];
            // 一级用户分销等级
            $oneLevelDistributionInfo = $DistributionModel->where(['id' => $oneLevelUserInfo['distribution_level_id']])->find();

            $is_repurchase = 0;
            if ($totalCount > 1) { //复购
                $is_repurchase = 1;
                $oneCommission = isset($oneLevelDistributionInfo['one_level_repurchase_income']) ? $oneLevelDistributionInfo['one_level_repurchase_income'] : 0;
            } else {
                $oneCommission = isset($oneLevelDistributionInfo['one_level_income']) ? $oneLevelDistributionInfo['one_level_income'] : 0;
            }
        }
        $twoLevelUserInfo = [];
        if ($setting['is_level'] == 2) {
            if ($oneLevelUserInfo['pid'] > 0) { // 有二级上级
                $twoLevelUserInfo = $userModel->where(['id' => $oneLevelUserInfo['pid']])->find();
                $two_distribution_level = $twoLevelUserInfo['distribution_level'];
                $two_distribution_level_id = $twoLevelUserInfo['distribution_level_id'];
                $twoLevelDistributionInfo = $DistributionModel->where(['id' => $twoLevelUserInfo['distribution_level_id']])->find();
                if ($totalCount > 1) { //复购
                    $twoCommission = isset($twoLevelDistributionInfo['two_level_repurchase_income']) ? $twoLevelDistributionInfo['two_level_repurchase_income'] : 0;
                } else {
                    $twoCommission = isset($twoLevelDistributionInfo['two_level_income']) ? $twoLevelDistributionInfo['two_level_income'] : 0;

                }
            }
        }
        $memberModel = new FigureMember();
        $memberLog = new FigureMemberLog();
        $memberCount = [];  // 不同套餐的购买数量
        $memberTwoCount = [];  // 不同套餐的购买数量
        $DistributionList = $DistributionModel->order('level', 'desc')->where(['status' => 2])->select()->toArray();
        if ($setting['is_level'] >= 1) {
            $oneLevelUserJuniorUserList = $userModel->where(['pid' => $user['pid']])->select()->toArray(); // 获取此用户的上级用户的全部一级用户
            $oneLevelUserJuniorUserId = array_column($oneLevelUserJuniorUserList, 'id', ''); //

        }
        $oneLevelUserTwoUserList = [];
        // 获取此用户的上级用户的全部一级用户的购买会员数量
        if ($setting['is_level'] == 2) {
            // 此用户上级用户的 下下级用户
            $oneLevelUserTwoUserList = $userModel->where('pid', 'in', $oneLevelUserJuniorUserId)->select()->toArray(); // 获取此用户的一级用户的全部二级用户
            if ($oneLevelUserTwoUserList) {
                $oneLevelUserTwoUserId = array_column($oneLevelUserTwoUserList, 'id', '');  //
            }
            if ($twoLevelUserInfo) { // 有二级上级
                $twoLevelUserOneUserList = $userModel->where(['pid' => $twoLevelUserInfo['id']])->select()->toArray(); // 获取二级用户下的全部一级用户
                $twoLevelUserOneUserId = array_column($twoLevelUserOneUserList, 'id', ''); // 注这个可以不用加判断了 因为当用
                $twoLevelUserTwoUserList = $userModel->where('pid', 'in', $twoLevelUserOneUserId)->select()->toArray();
                $twoLevelUserTwoUserListId = array_column($twoLevelUserTwoUserList, 'id', ''); //
            }
        }

        // 上面都是 查用户 上级用户和上上级 用户

        if ($setting['is_open'] == 1) {
            $totalAmount = 0;
            $twoLevelUseTotalAmount = 0;
            if ($setting['distribution_mode'] == 1) { // 消费模式

                if ($setting['is_level'] >= 1) {

                    $memberBuyAmount = $memberLog->where('uid', 'in', $oneLevelUserJuniorUserId)
                        ->where(['pay_status' => 2])->sum('money');

                    $FigurePointLogModel = new FigurePointLog();
                    $PointBuyAmount = $FigurePointLogModel->where('uid', 'in', $oneLevelUserJuniorUserId)
                        ->where(['pay_status' => 2])->sum('money');
                    $totalAmount = bcadd($memberBuyAmount, $PointBuyAmount, 2);
                }

                if ($setting['is_level'] == 2) {
                    if ($oneLevelUserTwoUserList) {
                        $memberBuyAmount = $memberLog->where('uid', 'in', $oneLevelUserTwoUserId)
                            ->where(['pay_status' => 2])->sum('money');
                        $FigurePointLogModel = new FigurePointLog();
                        $PointBuyAmount = $FigurePointLogModel->where('uid', 'in', $oneLevelUserTwoUserId)
                            ->where(['pay_status' => 2])->sum('money');
                        $totalAmount = bcadd($memberBuyAmount, $PointBuyAmount, 2);
                    }

                    if ($twoLevelUserInfo) {
                        $twoLevelUserOneMemberBuyAmount = $memberLog->where('uid', 'in', $twoLevelUserOneUserId)->where(['pay_status' => 2])
                            ->where(['pay_status' => 2])->sum('money');
                        $twoLevelUserOnePointBuyAmount = $FigurePointLogModel->where('uid', 'in', $twoLevelUserOneUserId)->where(['pay_status' => 2])
                            ->where(['pay_status' => 2])->sum('money');
                        $twoLevelUserOneAmount = bcadd($twoLevelUserOneMemberBuyAmount, $twoLevelUserOnePointBuyAmount, 2);
                        $twoLevelUserTwoMemberBuyAmount = $memberLog->where('uid', 'in', $twoLevelUserTwoUserListId)->where(['pay_status' => 2])
                            ->where(['pay_status' => 2])->sum('money');
                        $twoLevelUserTwoPointBuyAmount = $FigurePointLogModel->where('uid', 'in', $twoLevelUserTwoUserListId)->where(['pay_status' => 2])
                            ->where(['pay_status' => 2])->sum('money');
                        $twoLevelUserTwoAmount = bcadd($twoLevelUserTwoMemberBuyAmount, $twoLevelUserTwoPointBuyAmount, 2);
                        $twoLevelUseTotalAmount = bcadd($twoLevelUserOneAmount, $twoLevelUserTwoAmount, 2);

                    }
                }

                foreach ($DistributionList as $value) {

                    if ($totalAmount >= $value['consumption_amount']) {
                        $one_distribution_level = $value['level'];
                        $one_distribution_level_id = $value['id'];
                        break;
                    }
                }
                foreach ($DistributionList as $value) {
                    if ($twoLevelUseTotalAmount >= $value['consumption_amount']) {
                        $two_distribution_level = $value['level'];
                        $two_distribution_level_id = $value['id'];
                        break;
                    }
                }


            } else { // 购买套餐模式
                $memberList = $memberModel->select()->toArray();
                foreach ($memberList as $memberKey => $memberValue) {

                    $memberCount[$memberValue['id']] = 0;
                    $memberTwoCount[$memberValue['id']] = 0;

                }
                if ($setting['is_level'] >= 1 && $oneLevelUserInfo) {
                    $oneLevelUserJuniorUserMemberBuyCount = $memberLog->where('uid', 'in', $oneLevelUserJuniorUserId)->where(['pay_status' => 2])->field('member_id,count(*) as member_id_count ')->group('member_id')->select()->toArray();
                    if ($oneLevelUserJuniorUserMemberBuyCount) {  // 一级用户购买不同会员套餐的用户数量
                        $oneLevelUserJuniorUserMemberBuyId = array_column($oneLevelUserJuniorUserMemberBuyCount, 'member_id_count', 'member_id');
                        foreach ($memberCount as $memberCountKey => $countValue) {
                            if (array_key_exists($memberCountKey, $oneLevelUserJuniorUserMemberBuyId)) {
                                $memberCount[$memberCountKey] += $oneLevelUserJuniorUserMemberBuyId[$memberCountKey];
                            }
                        }
                    }
                }
                if ($setting['is_level'] == 2) {
                    if ($oneLevelUserTwoUserList) {
                        $oneLevelUserTwoUserMemberBuyCount = $memberLog->where('uid', 'in', $oneLevelUserTwoUserId)->where(['pay_status' => 2])->field('member_id,count(*) as member_id_count ')->group('member_id')->select()->toArray();
                        if ($oneLevelUserTwoUserMemberBuyCount) {  // 一级用户购买不同会员套餐的用户数量
                            $oneLevelUserTwoUserMemberBuyId = array_column($oneLevelUserTwoUserMemberBuyCount, 'member_id_count', 'member_id');
                            foreach ($memberCount as $memberCountKey => $countValue) {
                                if (array_key_exists($memberCountKey, $oneLevelUserTwoUserMemberBuyId)) {
                                    $memberCount[$memberCountKey] += $oneLevelUserTwoUserMemberBuyId[$memberCountKey];
                                }
                            }
                        }
                    }

                    //  这里查此用户上上级用户数据 ,如果没开启二级 上上级数据了没必要去查了
                    if ($twoLevelUserInfo) {
                        $twoLevelUserOneUserMemberBuyCount = $memberLog->where('uid', 'in', $twoLevelUserOneUserId)->where(['pay_status' => 2])->field('member_id,count(*) as member_id_count ')->group('member_id')->select()->toArray();
                        // 获取此用户的二级用户的全部一级用户的购买会员数量
                        if ($twoLevelUserOneUserMemberBuyCount) {
                            $twoLevelUserOneUserMemberBuyId = array_column($twoLevelUserOneUserMemberBuyCount, 'member_id_count', 'member_id');
                            foreach ($memberTwoCount as $memberTwoCountKey => $countTwoValue) {
                                if (array_key_exists($memberTwoCountKey, $twoLevelUserOneUserMemberBuyId)) {
                                    $memberTwoCount[$memberTwoCountKey] += $twoLevelUserOneUserMemberBuyId[$memberTwoCountKey];
                                }
                            }
                        }  // 此用户的二级用户 下级二级用户

                        $twoLevelUserTwoUserMemberBuyCount = $memberLog->where('uid', 'in', $twoLevelUserTwoUserListId)->where(['pay_status' => 2])->field('member_id,count(*) as member_id_count ')->group('member_id')->select()->toArray();
                        if ($twoLevelUserTwoUserMemberBuyCount) {
                            $twoLevelUserTwoUserMemberBuyId = array_column($twoLevelUserTwoUserMemberBuyCount, 'member_id_count', 'member_id');
                            foreach ($memberTwoCount as $memberTwoCountKey => $countTwoValue) {
                                if (array_key_exists($memberTwoCountKey, $twoLevelUserTwoUserMemberBuyId)) {
                                    $memberTwoCount[$memberTwoCountKey] += $twoLevelUserTwoUserMemberBuyId[$memberTwoCountKey];
                                }
                            }
                        }
                    }
                }

                foreach ($DistributionList as $DistributionKey => $DistributionValue) {
                    $packageArray = json_decode($DistributionValue['package_josn'], true);
                    if (isset($memberCount[$packageArray['package_id']])) {
                        if ($packageArray['package_count'] <= $memberCount[$packageArray['package_id']]) {
                            $one_distribution_level = $DistributionValue['level'];
                            $one_distribution_level_id = $DistributionValue['id'];
                            break;
                        }
                    }
                }
                foreach ($DistributionList as $DistributionKey => $DistributionValue) {
                    $packageArray = json_decode($DistributionValue['package_josn'], true);
                    if (isset($memberTwoCount[$packageArray['package_id']])) {
                        if ($packageArray['package_count'] <= $memberTwoCount[$packageArray['package_id']]) {
                            $two_distribution_level = $DistributionValue['level'];
                            $two_distribution_level_id = $DistributionValue['id'];
                            break; // 找到最高级就不找了
                        }
                    }
                }
            }

            if ($oneLevelUserInfo) {
                if ($setting['self_purchase_swich'] == 1) {
                    $oneUserBuyCount = $memberLog->where(['uid' => $oneLevelUserInfo['id'], 'pay_status'=> 2,'member_id' => $setting['self_purchase_member_id']])->count();
                    //   if ($oneUserBuyCount > 0) {
                    if ($one_distribution_level && $one_distribution_level_id) {
                        if ($oneLevelUserInfo['distribution_level_logic'] == 1) {
                            $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                        } elseif ($oneLevelUserInfo['distribution_level_logic'] == 2) {

                            if ($one_distribution_level > $oneLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                            }
                        } elseif ($oneLevelUserInfo['distribution_level_logic'] == 3) {
                            if ($one_distribution_level < $oneLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                            }
                        }
                    }
                    if ($oneUserBuyCount > 0 || $oneLevelUserInfo['distribution_level_logic'] > 1) {
                        if ($oneCommission > 0) {
                            $CommissionAmount = bcdiv(bcmul($amount, $oneCommission, 2), 100, 2);
                            $userModel->where(['id' => $user['pid']])->inc('brokerage', $CommissionAmount)->update();
                            $brokerageLog = [
                                'log_no' => $log_no,
                                'type' => $type,
                                'pid' => $user['pid'],
                                'uid' => $user['id'],
                                'total' => $amount,
                                'money' => $CommissionAmount,
                                'create_time' => time(),
                                'is_repurchase' => $is_repurchase,
                                'distribution_level_id' => $oneLevelDistributionInfo['id'],
                                'distribution_level' => $oneLevelDistributionInfo['level'],
                                'commission_level' => 1,
                            ];
                            $brokerage = new FigureBrokerageLog();
                            $brokerage->insert($brokerageLog);
                        }
                    }
//                    }
                } else {
                    if ($one_distribution_level && $one_distribution_level_id) {
                        if ($oneLevelUserInfo['distribution_level_logic'] == 1) {
                            $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                        } elseif ($oneLevelUserInfo['distribution_level_logic'] == 2) {
                            if ($one_distribution_level > $oneLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                            }
                        } elseif ($oneLevelUserInfo['distribution_level_logic'] == 3) {
                            if ($one_distribution_level < $oneLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $user['pid']])->update(['distribution_level' => $one_distribution_level, 'distribution_level_id' => $one_distribution_level_id]);
                            }
                        }
                    }
                    if ($oneCommission > 0) {
                        $CommissionAmount = bcdiv(bcmul($amount, $oneCommission, 2), 100, 2);
                        $userModel->where(['id' => $user['pid']])->inc('brokerage', $CommissionAmount)->update();
                        $brokerageLog = [
                            'log_no' => $log_no,
                            'type' => $type,
                            'pid' => $user['pid'],
                            'uid' => $user['id'],
                            'total' => $amount,
                            'money' => $CommissionAmount,
                            'create_time' => time(),
                            'is_repurchase' => $is_repurchase,
                            'distribution_level_id' => $oneLevelDistributionInfo['id'],
                            'distribution_level' => $oneLevelDistributionInfo['level'],
                            'commission_level' => 1,
                        ];
                        $brokerage = new FigureBrokerageLog();
                        $brokerage->insert($brokerageLog);
                    }
                }
            }

            if ($twoLevelUserInfo) {
                if ($setting['self_purchase_swich'] == 1) {

                    if ($two_distribution_level && $two_distribution_level_id) {

                        if ($twoLevelUserInfo['distribution_level_logic'] == 1) {
                            $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                        } elseif ($twoLevelUserInfo['distribution_level_logic'] == 2) {
                            if ($two_distribution_level > $twoLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                            }
                        } elseif ($twoLevelUserInfo['distribution_level_logic'] == 3) {
                            if ($two_distribution_level < $twoLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                            }
                        }

                    }
                    $twoUserBuyCount = $memberLog->where(['uid' => $twoLevelUserInfo['id'],'pay_status'=> 2, 'member_id' => $setting['self_purchase_member_id']])->count();

                    if ($twoUserBuyCount > 0 || $twoLevelUserInfo['distribution_level_logic'] > 1) {
                        if ($twoCommission > 0) {
                            $towCommissionAmount = bcdiv(bcmul($amount, $twoCommission, 2), 100, 2);
                            $brokerageTwoLog = [
                                'log_no' => $log_no,
                                'type' => $type,
                                'pid' => $oneLevelUserInfo['pid'],
                                'uid' => $user['id'],
                                'total' => $amount,
                                'money' => $towCommissionAmount,
                                'create_time' => time(),
                                'is_repurchase' => $is_repurchase,
                                'distribution_level_id' => $twoLevelDistributionInfo['id'],
                                'distribution_level' => $twoLevelDistributionInfo['level'],
                                'commission_level' => 2,
                            ];
                            $brokerage = new FigureBrokerageLog();
                            $brokerage->insert($brokerageTwoLog);
                            $userModel->where(['id' => $oneLevelUserInfo['pid']])->inc('brokerage', $towCommissionAmount)->update();
                        }

                    }

                } else {
                    if ($two_distribution_level && $two_distribution_level_id) {

                        if ($twoLevelUserInfo['distribution_level_logic'] == 1) {
                            $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                        } elseif ($twoLevelUserInfo['distribution_level_logic'] == 2) {
                            if ($two_distribution_level > $twoLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                            }
                        } elseif ($twoLevelUserInfo['distribution_level_logic'] == 3) {
                            if ($two_distribution_level < $twoLevelUserInfo['distribution_level']) {
                                $userModel->where(['id' => $oneLevelUserInfo['pid']])->update(['distribution_level' => $two_distribution_level, 'distribution_level_id' => $two_distribution_level_id]);

                            }
                        }

                    }
                    if ($twoCommission > 0) {
                        $towCommissionAmount = bcdiv(bcmul($amount, $twoCommission, 2), 100, 2);
                        $brokerageTwoLog = [
                            'log_no' => $log_no,
                            'type' => $type,
                            'pid' => $oneLevelUserInfo['pid'],
                            'uid' => $user['id'],
                            'total' => $amount,
                            'money' => $towCommissionAmount,
                            'create_time' => time(),
                            'is_repurchase' => $is_repurchase,
                            'distribution_level_id' => $twoLevelDistributionInfo['id'],
                            'distribution_level' => $twoLevelDistributionInfo['level'],
                            'commission_level' => 2,
                        ];
                        $brokerage = new FigureBrokerageLog();
                        $brokerage->insert($brokerageTwoLog);
                        $userModel->where(['id' => $oneLevelUserInfo['pid']])->inc('brokerage', $towCommissionAmount)->update();
                    }
                }
            }


        }
        //  一级用户

    }

    public function advertisingRewards(){
        $uid = input('uid');
        $system = FigureSystem::where("id", 1)->find();
        $balanceLog = new FigureBalanceLog();
        $user = FigureUser::where("id", $uid)->find();
        $log_no = getPayNo('ar');
        if ($system['banner_num']){
            $balanceLog->save([
                'uid' => $uid,
                'log_no' => $log_no,
                'type' => 1,
                'way' => 55,
                'current' => $user['balance'],
                'money' => $system['banner_num'],
                'desc' => '观看广告奖励'
            ]);

            $user->save([
                'balance' => Db::raw('balance+' . $system['banner_num'])
            ]);
        }
        return result(0, '成功');
    }


}